﻿#include "unrealircd.h"

CMD_FUNC(cmd_resetPassword);

ModuleHeader MOD_HEADER
= {
	"third/resetpassword",
	"1.1",
	"This module will send phone message ",
	"waitch",
	"unrealircd-5",  
};

MOD_INIT()
{
	CommandAdd(modinfo->handle, "RESETPASSWORD", cmd_resetPassword, 5, CMD_UNREGISTERED|CMD_UNLOGIN|CMD_USER);
	

	return MOD_SUCCESS;
}

MOD_LOAD()
{
	return MOD_SUCCESS;
}

MOD_UNLOAD()
{
	return MOD_SUCCESS;
}


/**
 * 重设密码
 * parv[1] 用户名
 * parv[2] 验证方式
 * parv[3] 验证码发送目标
 * parv[4] 验证码
 * parv[5] 新密码
 */
CMD_FUNC(cmd_resetPassword){
    if (!IsAPPIdent(client)) {
		sendnumeric(client, ERR_WHITHOUTAPPIDENT);
		return;
	}
	if (parc != 6 || BadPtr(parv[5])) {
		sendnumeric(client, ERR_NEEDMOREPARAMS, "RESETPASSWORD");
		return;
	}
    int data_len = 0;
    D_User *d_user = queryImUserByUserName(parv[1],&data_len);
    if (data_len!=1){
        db_D_UserFree(d_user,data_len);
        sendnumeric(client, USERNOTEXIT, parv[1]);
		return;
    }

    int sendtype=atoi(parv[2]);
	char *sendValue=NULL;
	switch(sendtype){
		case(SMS_MODE_PHONE)://验证短信发送的验证码是否正确
			if(strcmp(d_user->tel,parv[3])){
				sendValue = NULL;
			}
			else{
				safe_strdup(sendValue,parv[3]);
			}
			break;
		case(SMS_MODE_EMAIL)://验证邮箱发送的验证码是否正确
			{
				int temp_user_email_len =0;
				D_im_user_email * temp_user_email = queryImUserEmailByIdAndEmail(*(d_user->id),parv[3],&temp_user_email_len);
				if(temp_user_email_len != 1){
					sendValue =NULL;
				}
				else{
					safe_strdup(sendValue,parv[3]);
				}
				db_D_UserEmailFree(temp_user_email,temp_user_email_len);
				break;
			}
		default:
			sendnumeric(client, PARAMERROR, "RESETPASSWORD","parv[2]");
            db_D_UserFree(d_user,data_len);
			return;
	}
	if(!sendValue){
        db_D_UserFree(d_user,data_len);
		sendnumeric(client, PARAMERROR, "RESETPASSWORD","parv[2]");
		return;
	}
	//判断验证码是否有效
	if(!D_SMSVerificationCode(sendValue,parv[4],sendtype,SMS_STATUS_RESET_PASSWORD)){
		sendnumeric(client, SMSVALIDATIONFAILED);
		return;
	}
    //更改新密码
    safe_free(d_user->user_password);
	safe_strdup(d_user->user_password,parv[5]);
    int user_updata=0;
	char user_updata_error[255]="";
    D_User * d_user_update = updataImUser(d_user,&user_updata,user_updata_error);
    if(user_updata==-1){
        ircd_log(LOG_ERROR,"RESETPASSWORD sql error:%s",user_updata_error);
		sendnumeric(client, RESETPASSWORDFAILE, d_user->user_name);
        db_D_UserFree(d_user,data_len);
        db_D_UserFree(d_user_update,user_updata);
		return;
	}
    sendnumeric(client, RESETPASSWORDSUCCESS);
    if((client->user_id)==*(d_user->id)){
        exit_client(client,NULL,"reset password,please relogin");
    }
    db_D_UserFree(d_user,data_len);
    db_D_UserFree(d_user_update,user_updata);
    
}